package com.sg.common.empty.service;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sg.common.dao.BaseDao;
import com.sg.common.empty.core.AsyncTree;
import com.sg.common.empty.core.EasyOut;
import com.sg.common.empty.core.EpUtil;
import com.sg.common.empty.core.FilterVal;
import com.sg.common.empty.core.JspUtil3;
import com.sg.common.empty.core.NameValuePair;
import com.sg.common.empty.entity.Cons;
import com.sg.common.empty.entity.Domain;
import com.sg.common.empty.entity.Myinput;
import com.sg.common.empty.entity.PerfProperty;
import com.sg.common.empty.entity.Property;
import com.sg.common.empty.entity.TableBean;
import com.sg.common.empty.json.Filter;
import com.sg.common.empty.json.Nsecs;
import com.sg.common.empty.json.Prop;
import com.sg.common.empty.json.SecTable;
import com.sg.common.empty.web.ListDcBuilder;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;
import com.sg.common.utils.ReUtils;
import com.sg.common.utils.StrUtil;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigList;
import com.typesafe.config.ConfigUtil;
import com.typesafe.config.ConfigValue;

/**
 * 请假实体管理接口
 * 
 * @author HenryYan
 * @param <T>
 * @param <T>
 */
@Component
public class CfgService extends BaseDao {

	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 将bean中的涉及到pps的属性放入数据库的oldBean中
	 * 
	 * @param request
	 * @param bean
	 * @param pps
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws NoSuchFieldException
	 */
	public Object copyProsToOldForUpdate(HttpServletRequest request,
			Object bean, List<PerfProperty> pps) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			NoSuchFieldException {
		DetachedCriteria dc = DetachedCriteria.forClass(bean.getClass());
		dc.add(Restrictions.eq(Constant.ID, ReUtils.getStr(bean, "id")));
		Object old = findBean(dc);
		for (PerfProperty pp : pps) {
			String esh = JspUtil3.propertyValue(pp, "esh");
			if (StringUtils.equals("2", esh)) {
				ReUtils.copyValue(bean, old, pp.getProperty().getProperty());
			}
		}
		// Util.setOTMNull(oran, old, baseDao);
		if (ReUtils.contain(bean, "updateDate"))
			ReUtils.set(old, "updateDate", DateTimeUtils.formatDate(
					new Timestamp(System.currentTimeMillis()),
					"yyyy-MM-dd HH:mm"));
		if (ReUtils.contain(bean, "updateMember"))
			ReUtils.set(old, "updateMember",
					request.getSession().getAttribute(Constant.SESSION_MEMBER));
		return old;
	}

	public Object copyProsToOldForUpdate_Map(HttpServletRequest request,
			Object bean, List<PerfProperty> pps) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			NoSuchFieldException {
		DetachedCriteria dc = DetachedCriteria.forEntityName(ReUtils.getStr(
				bean, Constant.BEAN_TYPE));
		dc.add(Restrictions.eq(Constant.ID, ReUtils.getStr(bean, "id")));
		Object old = findBean(dc);
		for (PerfProperty pp : pps) {

			String property = pp.getProperty().getProperty();
			Map beanMap = (HashMap) bean;
			if (beanMap.containsKey(property)) {
				ReUtils.copyValue(bean, old, property);
			}
		}
		// Util.setOTMNull(oran, old, baseDao);
		ReUtils.set(old, "updateDate", DateTimeUtils.formatDate(new Timestamp(
				System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
		ReUtils.set(old, "updateMember",
				request.getSession().getAttribute(Constant.SESSION_MEMBER));
		return old;
	}

	public void beforeSave_Map(Object forSave, HttpServletRequest request)
			throws NoSuchFieldException, IllegalAccessException,
			ClassNotFoundException, InvocationTargetException,
			NoSuchMethodException {
		// Util.setOTMNull(oran, forSave, baseDao);
		ReUtils.set(forSave, "createDate", DateTimeUtils.formatDate(
				new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
		ReUtils.set(forSave, "createMember",
				request.getSession().getAttribute(Constant.SESSION_MEMBER));
		ReUtils.set(forSave, "usrct", Constant.get("USRCT"));
	}

	public void beforeSave(Object forSave, Filter filter,
			HttpServletRequest request) throws NoSuchFieldException,
			IllegalAccessException, ClassNotFoundException,
			InvocationTargetException, NoSuchMethodException {
		// Util.setOTMNull(oran, forSave, baseDao);
		if (ReUtils.contain(forSave, "createDate"))
			ReUtils.set(forSave, "createDate", DateTimeUtils.formatDate(
					new Timestamp(System.currentTimeMillis()),
					"yyyy-MM-dd HH:mm"));
		if (ReUtils.contain(forSave, "createMember"))
			ReUtils.set(forSave, "createMember", request.getSession()
					.getAttribute(Constant.SESSION_MEMBER));
		// saveFilter(filter, forSave);
		// idField.set(bean, Util.generateId());
		if (ReUtils.contain(forSave, "usrct"))
			ReUtils.set(forSave, "usrct", Constant.get("USRCT"));
	}

	/**
	 * 各sectiontable中涉及到的PerfPropertys
	 * 
	 * @param bean
	 * @param ne2
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 */
	public List<PerfProperty> ppsInSecTables(Object bean, Nsecs ne)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, InstantiationException,
			ClassNotFoundException {
		SecTable[] sts = ne.getSts();
		List<PerfProperty> pps = new ArrayList<PerfProperty>();
		for (SecTable st : sts) {
			List<PerfProperty> searches = searches(bean, st.getProps());
			pps.addAll(searches);
		}
		return pps;
	}

	//
	// public Object ndetail(Object tableBean, Object bean, Perf perf,
	// List<Permission> specialPermission, HttpServletRequest request)
	// throws IllegalAccessException, InvocationTargetException,
	// NoSuchMethodException, ClassNotFoundException,
	// NoSuchFieldException, InstantiationException {
	// String layout = perf.getLayout();
	// Nsecs ne = JSON.parseObject(layout, Nsecs.class);
	// SecTable[] sts = ne.getSts();
	// SecList[] sls = ne.getSls();
	// List<SectionDraw> sds = new ArrayList<SectionDraw>();
	// List<PerfProperty> pps = new ArrayList<PerfProperty>();
	// for (SecTable st : sts) {
	// SectionDraw sd = new SectionDraw();
	// List<PerfProperty> searches = searches(bean, st.getProps());
	// sd.setPps(searches);
	// pps.addAll(searches);
	// PropertyUtils.copyProperties(sd, st);
	// sds.add(sd);
	// }
	//
	// buildPropertyShowValueInMap(bean, pps, "");
	//
	// StringBuilder js = new StringBuilder();
	// js.append(JspUtil3.findSaveSubmitJs());
	// @SuppressWarnings("unchecked")
	// List<Permission> perfPermission = (List<Permission>) request
	// .getAttribute("perfPermission");
	//
	// StringBuilder body = JspUtil3.ndetail(request.getRequestURI(),
	// tableBean, bean, perf, ReUtils.getStr(bean, "id"),
	// request.getParameter("ids"), specialPermission, perfPermission,
	// sds, sls);
	//
	// return EpUtil.commonView(body, js, request);
	// }

	public List<PerfProperty> searches(Object bean, Prop[] props)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, InstantiationException,
			ClassNotFoundException {
		List<PerfProperty> ppl = new ArrayList<PerfProperty>();
		if (ArrayUtils.isNotEmpty(props)) {
			for (Prop prop : props) {

				// 在pn带taskkey，bean带taskkey的情况下，判断pn所带的taskkey属性是否包含当前的流程环节,不包含则不显示
				String pnTaskKey = prop.getTaskKey();
				String js = prop.getJs();
				boolean cando = true;
				if (StringUtils.isNotEmpty(pnTaskKey)) {
					String beanTaskKey = ReUtils.getStr(bean, "taskKey");
					if (StringUtils.isNotEmpty(beanTaskKey)
							&& !StrUtil.contains(beanTaskKey, pnTaskKey)) {
						cando = false;
					}
				}
				if (StringUtils.isNotEmpty(js)) {
					ScriptEngineManager factory = new ScriptEngineManager();// step
																			// 1
					ScriptEngine engine = factory.getEngineByName("JavaScript");// Step
																				// 2
					engine.put("bean", bean);
					try {
						engine.eval(js);
						cando = (Boolean) engine.get("cando");
					} catch (ScriptException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				if (cando) {
					String pnx = prop.getPn();
					String[] pns = StringUtils.split(pnx, ",");
					String className;
					// ===================================dym
					if (bean instanceof Map) {
						Map beanMap = (Map) bean;
						className = (String) beanMap.get(Constant.BEAN_TYPE);
						for (String pn : pns) {
							createPpByPn(ppl, prop, className, pn);
						}
					}
					// ===================================dym
					else {
						className = bean.getClass().getName();
						for (String pn : pns) {
							if (ReUtils.contain(bean, pn)) {
								createPpByPn(ppl, prop, className, pn);
							} else {
								logger.error(
										"解析treeList.json时，属性{}不存在于{}的Class中",
										pn, className);
							}
						}
					}
				}
			}
		}
		return ppl;
	}

	public List<PerfProperty> emptySearches(HttpServletRequest request,
			String tableName, ConfigList pns)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, InstantiationException,
			ClassNotFoundException {
		List<PerfProperty> ppl = new ArrayList<PerfProperty>();
		if (pns == null) {
			//TODO 如果为空应该把数据数据表的属性全部放进去
			return ppl;
		}
		for (int i = 0; i < pns.size(); i++) {
			Config data = pns.get(i).atKey("pp");
			String pnx = Constant.get(data, "pp.pn");
			String descr = Constant.get(data, "pp.descr");
			String esh = Constant.get(data, "pp.esh");
			String[] pnitems = StringUtils.split(pnx, ",");
			for (String pn : pnitems) {
				String fullProName = pn;
				if (!pn.contains(".")) {
					fullProName = tableName + "." + pn;
				}
				Property property = Constant.EMPTYPROPS.get(fullProName);
				if (property != null) {
					PerfProperty pp = new PerfProperty();
					if (pn.contains("."))
						property.setProperty(pn);
					pp.setProperty(property);
					pp.setShowvalue(property.getShowvalue());// 在需要showvalue的场合用到
					if (StringUtils.isNotEmpty(descr))
						pp.setDescr(descr);
					if (StringUtils.isNotEmpty(esh))
						pp.setEsh(esh);
					else {
						pp.setEsh("2");
					}
					ppl.add(pp);
				}
			}
		}
		return ppl;
	}

	private void createPpByPn(List<PerfProperty> ppl, Prop prop,
			String className, String pn) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		if (pn.indexOf(".") > 0) {
			String[] split = StringUtils.split(pn, ".");
			// 得到aa。bb属性、
			// DetachedCriteria dc = DetachedCriteria.forClass(Property.class);
			// dc.createAlias("bean", "bean");
			// dc.add(Restrictions.eq("bean.className", className)).add(
			// Restrictions.eq("property", split[0]));
			// Property property = findBean(dc);
			Property property = Constant.BEANPROPMAP.get(className + "_"
					+ split[0]);
			if (property != null) {
				// dc = DetachedCriteria.forClass(Property.class);
				// dc.createAlias("bean", "bean");
				// dc.add(Restrictions.eq("bean.className",
				// property.getVotype()))
				// .add(Restrictions.eq("property", split[1]));
				// Property nestProperty = findBean(dc);
				Property nestProperty = Constant.BEANPROPMAP.get(property
						.getVotype() + "_" + split[1]);
				if (nestProperty != null) {
					PerfProperty pp = new PerfProperty();
					Property nProperty = new Property();
					nProperty.setProperty(pn);// 取到bb的property后，将aa.bb赋予bbProperty的field
					nProperty.setDescr(property.getDescr() + "-"
							+ nestProperty.getDescr());
					nProperty.setMyinput(nestProperty.getMyinput());
					Property voProperty = Constant.BEANPROPMAP.get(property
							.getVotype() + "_" + split[split.length - 1]);
					if (voProperty != null) {
						nProperty.setVotype(nestProperty.getVotype());
						pp.setValueurl(voProperty.getValueurl());
					}
					pp.setProperty(nProperty);
					pp.setShowvalue(nestProperty.getShowvalue());// 在需要showvalue的场合用到

					PropertyUtils.copyProperties(pp, prop);
					ppl.add(pp);
				} else {
					logger.error("解析treeList.json时，属性{}不存在于{}对应的数据库属性列表", pn,
							property.getBean().getClass().getName());
				}
			}
		} else {
			// Property property = findPropertyBeanByName(pn, className);
			Property property = Constant.BEANPROPMAP.get(className + "_" + pn);
			if (property != null) {
				PerfProperty pp = new PerfProperty();
				pp.setProperty(property);
				PropertyUtils.copyProperties(pp, prop);
				ppl.add(pp);
			} else {
				logger.error("解析treeList.json时，属性{}不存在于{}对应的数据库属性列表", pn,
						className);
			}
		}
	}

	// private Property findPropertyBeanByName(String pn, String className) {
	// DetachedCriteria dc = DetachedCriteria.forClass(Property.class);
	// dc.createAlias("bean", "bean");
	// dc.add(Restrictions.eq("bean.className", className)).add(
	// Restrictions.eq("property", pn));
	// Property property = findBean(dc);
	// return property;
	// }

	// @Transactional(readOnly = true)
	// public Object listDate(List<PerfProperty> listPl, Object bean,
	// List<PerfProperty> searchPl, HttpServletRequest request,
	// CfgService service, String lSort, String lOrder)
	// throws NoSuchFieldException, ClassNotFoundException,
	// IllegalAccessException, InvocationTargetException,
	// NoSuchMethodException, InstantiationException {
	// EasyOut<Object> coeo = new EasyOut<Object>();
	// Filter filter = (Filter) request.getAttribute("filter");
	// String sort = request.getParameter("sort");
	// String order = request.getParameter("order");
	// if (StringUtils.isEmpty(sort))
	// sort = lSort;
	// if (StringUtils.isEmpty(order))
	// order = lOrder;
	//
	// String sql = request.getParameter("_sql");
	// String pre = request.getParameter("p_re");
	// // String pre = "this_.bean='8a8aa68f53ef3fb60153ef5d331e0001'";
	// if (StringUtils.isNotEmpty(pre))
	// pre = pre.replace("=", "='") + "'";
	// Integer page = 1;
	// if (request.getParameter("page") != null)
	// page = Integer.valueOf(request.getParameter("page"));
	// Integer rows = 10;
	// if (request.getParameter("rows") != null)
	// rows = Integer.valueOf(request.getParameter("rows"));
	// // coeo.setTotal(service.findCount(buildDc("count", sort, order,
	// // bean, searchPl, filter, sql,pre)));
	// // List<Object> cl = service.findWithPage2(
	// // buildDc("", sort, order, bean, searchPl, filter, sql,pre),
	// // (page - 1) * rows, rows);
	//
	// coeo.setTotal(findCount(ListDcBuilder.countDcBuilder(bean, searchPl,
	// filter, sql, pre, service).buildDc()));
	//
	// DetachedCriteria dCriteria = ListDcBuilder.listDcBuilder(sort, order,
	// bean, searchPl, filter, sql, pre, service).buildDc();
	// List<Object> cl = findWithPage2(dCriteria, (page - 1) * rows, rows);
	// for (Object obj : cl) {
	// buildPropertyShowValueInMap(obj, listPl, "");
	// }
	// coeo.setRows(cl);
	// return coeo;
	// }

	@Transactional(readOnly = true)
	public Object emptyListDate(List<PerfProperty> listPl,
			List<PerfProperty> searchPl, HttpServletRequest request,
			CfgService service, Config data) throws NoSuchFieldException,
			ClassNotFoundException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			InstantiationException {
		EasyOut<Map<String, Object>> coeo = new EasyOut<Map<String, Object>>();

		ConfigList listPn = Constant.getList(data, "data.listPn");
		String tSql = Constant.getT(data, "data.tSql", String.class);
		List<String> params = Constant.getStringList(data, "data.params");

		String sort = request.getParameter("sort");
		String order = request.getParameter("order");

		if (StringUtils.isEmpty(sort) && StringUtils.isEmpty(order)) {
				sort = Constant.get(data,"data.sort");
				order = Constant.get(data,"data.order");
		}

//		String sql = request.getParameter("_sql");
		String pre = request.getParameter("p_re");

		if (StringUtils.isNotEmpty(pre))
			pre = pre.replace("=", "='") + "'";

		Integer page = 1;
		if (request.getParameter("page") != null) {
			page = Integer.valueOf(request.getParameter("page"));
		} else if (data.hasPath("data.page")) {
			page = data.getInt("data.page");
		}
		Integer rows = 10;
		if (request.getParameter("rows") != null) {
			rows = Integer.valueOf(request.getParameter("rows"));
		} else if (data.hasPath("data.rows")) {
			rows = data.getInt("data.rows");
		}

		String header = (String) request.getAttribute("conf.header");
		String tableName = Constant.getT(header + ".tn",
				String.class);

		String conditon = EpUtil.buildCondition(searchPl, request);

		if (StringUtils.isNotEmpty(conditon))
			tSql = tSql + conditon;
		List<Object> sqlParams = EpUtil.transParams(service, params);
		String sqlString = "select count(1) " + tSql;
		System.out.println(sqlString);
		List<Object> countList = queryBySql("select count(1) " + tSql,
				sqlParams.toArray());

		coeo.setTotal(((BigInteger) countList.get(0)).intValue());

		String findData = "";
		List<String> listData = new ArrayList<String>();
		Iterator<ConfigValue> config = listPn.iterator();
		while (config.hasNext()) {
			ConfigValue configValue = (ConfigValue) config.next();
			Map<String, String> config2 = (Map<String, String>) configValue
					.unwrapped();
			String pnx = config2.get("pn");
			String alias = config2.get("alias");
			String[] pns = StringUtils.split(pnx, ",");
			for (String pn : pns) {
				if (StringUtils.isNotEmpty(alias))
					findData = findData + pn + " as " + alias + ",";
				else {
					if (pn.contains("."))
						findData = findData + pn + ",";
					else
						findData = findData + tableName + "." + pn + ",";
				}
				listData.add(pn);
			}
		}
		if (StringUtils.isNotEmpty(sort) && StringUtils.isNotEmpty(order)) {
			tSql = tSql + " order by " + sort + " " + order;
		} else {
			tSql = tSql + " order by id desc";
		}

		tSql = tSql + " limit " + (page - 1) * rows + "," + rows;

		findData = findData.substring(0, findData.length() - 1);
		List<Object> dataList = queryBySql("select " + findData + " " + tSql,
				sqlParams.toArray());

		// TODO 需增加，值表现时的封装方法.设想两种封装:1.后台默认方法 如showvalue以及其他预设方法 2.前台:通过使用pn中的js进行封装
		List<Map<String, Object>> mList = new ArrayList<Map<String, Object>>();
		for (Object obj : dataList) {
			int i = 0;
			Map<String, Object> map = new HashMap<String, Object>();
			for (String p : listData) {
				String[] ps = StringUtils.split(p, ".");
				if (ps.length > 1) {
					Map<String, Object> childMap = (Map<String, Object>) map
							.get(ps[0]);
					if (childMap == null)
						childMap = new HashMap<String, Object>();
					ReUtils.set(childMap, ps[1], ((Object[]) obj)[i]);
					ReUtils.set(map, ps[0], childMap);
				} else {
					ReUtils.set(map, p, ((Object[]) obj)[i]);
				}
				i++;
			}
			mList.add(map);
		}
		coeo.setRows(mList);
		return coeo;
	}

	

	// public List<AsyncTree> findCheckedTreeValue(List<String> mpl, Object
	// bean,
	// String id) throws NoSuchFieldException, IllegalAccessException,
	// InvocationTargetException, NoSuchMethodException {
	// List<AsyncTree> treeValue = new ArrayList<AsyncTree>();
	// if (StringUtils.isNotEmpty(id)) {
	// bean = get(bean.getClass(), id);
	// }
	// List<Object> pl = findByParent(bean, null);
	// for (Object bo : pl) {
	// AsyncTree at = new AsyncTree();
	// String boid = ReUtils.getStr(bo, "id");
	// String bodescr = ReUtils.getStr(bo, "descr");
	// at.setId(boid);
	// at.setText(bodescr);
	// if (mpl.contains(boid)) {
	// at.setChecked("true");
	// }
	// at.setState("open");
	// at.setChildren(findCheckedTreeValue(mpl, bean, boid));
	// treeValue.add(at);
	// }
	// return treeValue;
	// }

	// public List<AsyncTree> findTreeValue(Object bean, String id,
	// List<String> endToTopPathIds, List<String> descrs)
	// throws NoSuchFieldException, IllegalAccessException,
	// InvocationTargetException, NoSuchMethodException {
	// List<AsyncTree> treeValue = new ArrayList<AsyncTree>();
	// Object object = bean;
	// if (StringUtils.isNotEmpty(id)) {
	// object = get(bean.getClass(), id);
	// }
	// List<Object> pl = findByParent(object, bean);
	// for (Object bo : pl) {
	// AsyncTree at = new AsyncTree();
	//
	// String descrStr = ReUtils.mutiPropertyValue(descrs, bo);
	//
	// String boid = ReUtils.getStr(bo, "id");
	// at.setId(boid);
	// at.setText(descrStr.toString());
	// if (endToTopPathIds.contains(boid)
	// || endToTopPathIds.contains("all")) {
	// at.setChildren(findTreeValue(bean, boid, endToTopPathIds,
	// descrs));
	// at.setState("open");
	// } else {
	// if (CollUtil.isNotEmpty(findByParent(bo, bean))) {
	// at.setState("closed");
	// } else {
	// at.setState("open");
	// }
	// }
	// treeValue.add(at);
	// }
	// return treeValue;
	// }

	private List<Object> findByParent(Object p, Object bean)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		Class<? extends Object> clazz = p.getClass();
		DetachedCriteria dc = DetachedCriteria.forClass(clazz);
		// Field declaredField = clazz.getDeclaredField("id");
		// String pid = (String) declaredField.get(p);
		String pid = ReUtils.getStr(p, "id");
		if (!StringUtils.isNotEmpty(pid)) {
			dc.add(Restrictions.isNull("parent"));
		} else {
			dc.add(Restrictions.eq("parent", p));
		}
		if (bean != null && ReUtils.findField(bean, "orge") != null) {
			String orge = ReUtils.getStr(bean, "orge");
			if (StringUtils.isNotEmpty(orge)) {
				if (orge.indexOf(",") > 0) {
					dc.add(Restrictions.in("orge", orge.split(",")));
				} else {
					dc.add(Restrictions.eq("orge", orge));
				}
			}
//			if (StringUtils.isNotEmpty(orge)) {
//				dc.add(Restrictions.eq("orge", orge));
//			}
		}
		if (ReUtils.contain(p, "enable"))
			dc.add(Restrictions.eq("enable", "1"));
		List<Object> pl = find(dc);

		return pl;
	}

	/**
	 * 
	 * @param endTreeValue
	 * @param bean
	 * @param service
	 * @return
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 */
	public List<String> endToTopPathIds(String endTreeValue, Object bean)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		List<String> res = new ArrayList<String>();
		if ("all".equals(endTreeValue)) {
			res.add(endTreeValue);
			return res;
		}
		if (StringUtils.isNotEmpty(endTreeValue)) {
			Class<?> clazz = bean.getClass();
			Object baseTO = get(clazz, endTreeValue);
			Object parentObject = ReUtils.get(baseTO, "parent");

			if (parentObject != null) {

				String pid = ReUtils.getStr(parentObject, "id");
				res.add(pid);

				res.addAll(endToTopPathIds(pid, bean));
			}
		}
		return res;
	}

	public String findSelectValById(Object bean, String forDescr, String param)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		DetachedCriteria dc;
		// ===================================dym
		if (bean instanceof Map) {
			dc = DetachedCriteria.forEntityName(ReUtils.getStr(bean,
					Constant.BEAN_TYPE));
		}
		// ===================================dym
		else {
			Class<? extends Object> clazz = bean.getClass();
			dc = DetachedCriteria.forClass(clazz);
		}
		dc.add(Restrictions.eq("id", param));
		Object m = findBean(dc);
		List<String> descrs = EpUtil.findDescrPropertyByFd(forDescr);
		return ReUtils.mutiPropertyValue(descrs, m);
	}

	public List<NameValuePair> findSelectValue(Object bean, String q,
			String forDescr, String sort, String order)
			throws UnsupportedEncodingException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		List<NameValuePair> nl = new ArrayList<NameValuePair>();
		List<String> descrs = EpUtil.findDescrPropertyByFd(forDescr);
		String idFiledStr = Constant.ID;

		DetachedCriteria dc = selectDc(bean, q, descrs);

		if (ReUtils.contain(bean, "enable"))
			dc.add(Restrictions.eq("enable", "1"));

		if (StringUtils.isEmpty(sort)) {// 为空才需要设置默认的排序，非空则按非空要求进行排序
			if (ReUtils.findField(bean, "ord") != null) {
				sort = "ord";
				order = "asc";
			} else {
				sort = "id";
				order = "desc";
			}
		}
		if (StringUtils.isNotEmpty(sort) && !sort.contains(".")) {// !sort.contains(".")
			// ：在包含点号时，无法用其进行排序
			if ("desc".equals(order)) {
				dc.addOrder(Order.desc(sort));
			} else {
				dc.addOrder(Order.asc(sort));
			}
			dc.addOrder(Order.asc("id"));
		}
		List<Object> ml = find(dc);

		for (Object m : ml) {
			NameValuePair nameValuePair = new NameValuePair();
			nameValuePair.setId(ReUtils.getStr(m, idFiledStr));
			nameValuePair.setText(ReUtils.mutiPropertyValue(descrs, m));
			nl.add(nameValuePair);
		}
		return nl;
	}

	public List<NameValuePair> findSelectValue2(Object bean,
			List<PerfProperty> searchPl, String forDescr, String sort,
			String order) throws UnsupportedEncodingException,
			IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		List<NameValuePair> nl = new ArrayList<NameValuePair>();
		List<String> descrs = EpUtil.findDescrPropertyByFd(forDescr);
		String idFiledStr = Constant.ID;

		DetachedCriteria dc = selectDc2(bean, searchPl);

		if (ReUtils.contain(bean, "enable"))
			dc.add(Restrictions.eq("enable", "1"));

		if (StringUtils.isEmpty(sort)) {// 为空才需要设置默认的排序，非空则按非空要求进行排序
			if (ReUtils.findField(bean, "ord") != null) {
				sort = "ord";
				order = "asc";
			} else {
				sort = "id";
				order = "desc";
			}
		}
		if (StringUtils.isNotEmpty(sort) && !sort.contains(".")) {// !sort.contains(".")
			// ：在包含点号时，无法用其进行排序
			if ("desc".equals(order)) {
				dc.addOrder(Order.desc(sort));
			} else {
				dc.addOrder(Order.asc(sort));
			}
			dc.addOrder(Order.asc("id"));
		}
		List<Object> ml = find(dc);

		for (Object m : ml) {
			NameValuePair nameValuePair = new NameValuePair();
			nameValuePair.setId(ReUtils.getStr(m, idFiledStr));
			nameValuePair.setText(ReUtils.mutiPropertyValue(descrs, m));
			nl.add(nameValuePair);
		}
		return nl;
	}

	public Map<String, Object> findSelect2Value2(Object bean,
			List<PerfProperty> searchPl, String forDescr, String page,
			String rows, String sort, String order)
			throws UnsupportedEncodingException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		List<NameValuePair> nl = new ArrayList<NameValuePair>();
		List<String> descrs = EpUtil.findDescrPropertyByFd(forDescr);
		String idFiledStr = Constant.ID;

		DetachedCriteria dc1 = selectDc2(bean, searchPl);

		int count = findCount(dc1);
		DetachedCriteria dc = selectDc2(bean, searchPl);

		if (ReUtils.contain(bean, "enable"))
			dc.add(Restrictions.eq("enable", "1"));

		if (StringUtils.isEmpty(sort)) {// 为空才需要设置默认的排序，非空则按非空要求进行排序
			if (ReUtils.findField(bean, "ord") != null) {
				sort = "ord";
				order = "asc";
			} else {
				sort = "id";
				order = "desc";
			}
		}
		if (StringUtils.isNotEmpty(sort) && !sort.contains(".")) {// !sort.contains(".")
			// ：在包含点号时，无法用其进行排序
			if ("desc".equals(order)) {
				dc.addOrder(Order.desc(sort));
			} else {
				dc.addOrder(Order.asc(sort));
			}
			dc.addOrder(Order.asc("id"));
		}
		int pageNum = Integer.valueOf(page);
		int rowNum = 30;
		if (StrUtil.requestParamsNotEmpty(rows)) {
			rowNum = Integer.valueOf(rows);
		}
		List<Object> ml = findWithPage2(dc, (pageNum - 1) * rowNum, rowNum);
		for (Object m : ml) {
			NameValuePair nameValuePair = new NameValuePair();
			nameValuePair.setId(ReUtils.getStr(m, idFiledStr));
			nameValuePair.setText(ReUtils.mutiPropertyValue(descrs, m));
			nl.add(nameValuePair);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", nl);
		map.put("total_count", count);
		map.put("incomplete_results", false);
		return map;
	}

	public Map<String, Object> findSelect2Value(Object bean, String q,
			String forDescr, String page, String rows, String sort, String order)
			throws UnsupportedEncodingException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		List<NameValuePair> nl = new ArrayList<NameValuePair>();
		List<String> descrs = EpUtil.findDescrPropertyByFd(forDescr);
		String idFiledStr = Constant.ID;

		DetachedCriteria dc1 = selectDc(bean, q, descrs);

		if (ReUtils.contain(bean, "enable"))
			dc1.add(Restrictions.eq("enable", "1"));
		int count = findCount(dc1);

		DetachedCriteria dc = selectDc(bean, q, descrs);

		if (ReUtils.contain(bean, "enable"))
			dc.add(Restrictions.eq("enable", "1"));

		if (StringUtils.isEmpty(sort)) {// 为空才需要设置默认的排序，非空则按非空要求进行排序
			if (ReUtils.findField(bean, "ord") != null) {
				sort = "ord";
				order = "asc";
			} else {
				sort = "id";
				order = "desc";
			}
		}
		if (StringUtils.isNotEmpty(sort) && !sort.contains(".")) {// !sort.contains(".")
			// ：在包含点号时，无法用其进行排序
			if ("desc".equals(order)) {
				dc.addOrder(Order.desc(sort));
			} else {
				dc.addOrder(Order.asc(sort));
			}
			dc.addOrder(Order.asc("id"));
		}
		int pageNum = Integer.valueOf(page);
		int rowNum = 30;
		if (StrUtil.requestParamsNotEmpty(rows)) {
			rowNum = Integer.valueOf(rows);
		}
		List<Object> ml = findWithPage2(dc, (pageNum - 1) * rowNum, rowNum);
		for (Object m : ml) {
			NameValuePair nameValuePair = new NameValuePair();
			nameValuePair.setId(ReUtils.getStr(m, idFiledStr));
			nameValuePair.setText(ReUtils.mutiPropertyValue(descrs, m));
			nl.add(nameValuePair);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", nl);
		map.put("total_count", count);
		map.put("incomplete_results", false);
		return map;
	}

	private DetachedCriteria selectDc(Object bean, String q, List<String> descrs)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, UnsupportedEncodingException {
		DetachedCriteria dc;
		// ===================================dym
		if (bean instanceof Map) {
			dc = DetachedCriteria.forEntityName(ReUtils.getStr(bean,
					Constant.BEAN_TYPE));
		}
		// ===================================dym
		else {
			Class<? extends Object> clazz = bean.getClass();
			dc = DetachedCriteria.forClass(clazz);
		}
		if (StringUtils.isNotEmpty(q)) {// 有查询条件，则加入Restrictions参数
			String decodeQ = URLDecoder.decode(q, "utf-8");
			List<String> sl = new ArrayList<String>();
			for (String field : descrs) {
				int indexOf = field.indexOf(".");
				if (indexOf >= 0) {
					String f1 = field.substring(0, indexOf);
					if (!sl.contains(f1)) {
						dc.createAlias(f1, f1);
						sl.add(f1);
					}
				}
			}
			// 使用动态sql加入或者查询，问题：在多表查询时，会出现字段歧义的问题
			if (descrs.size() == 1) {
				dc.add(Restrictions.ilike(descrs.get(0), decodeQ,
						MatchMode.ANYWHERE));
			} else {// TODO to test
				Disjunction disjunction = Restrictions.disjunction();
				for (String descr : descrs) {
					disjunction.add(Restrictions.ilike(descr, decodeQ,
							MatchMode.ANYWHERE));
				}
				dc.add(disjunction);
			}
		}
		return dc;
	}

	private DetachedCriteria selectDc2(Object bean, List<PerfProperty> searchPl)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, UnsupportedEncodingException {
		DetachedCriteria dc;
		// ===================================dym
		if (bean instanceof Map) {
			dc = DetachedCriteria.forEntityName(ReUtils.getStr(bean,
					Constant.BEAN_TYPE));
		}
		// ===================================dym
		else {
			Class<? extends Object> clazz = bean.getClass();
			dc = DetachedCriteria.forClass(clazz);
		}

		List<String> sl = new ArrayList<String>();// 用于检测是否会发生duplicate alias错误
		if (bean != null) {
			String beanValue = "";
			int i = 0;
			for (PerfProperty pp : searchPl) {

				Property property = pp.getProperty();
				String field = property.getProperty();
				if (StringUtils.isNotEmpty(property.getVotype())) {// 对于类搜索，类的id作为搜索条件
					field += ".id";
				}
				beanValue = ReUtils.getStr(bean, field);
				int indexOf = field.indexOf(".");
				if (StringUtils.isNotEmpty(beanValue)) {
					Myinput input = JspUtil3.propertyMyinput(pp);

					if (input != null) {
						if (indexOf > 0) {
							String f1 = field.substring(0, indexOf);
							if (!sl.contains(f1)) {
								dc.createAlias(f1, f1);
								sl.add(f1);
							}

						}
						String inputType = input.getType();
						if (StringUtils.equals(inputType, "text")
								|| StringUtils.equals(inputType, "textarea")) {
							String s1 = beanValue.substring(1);
							if (beanValue.startsWith("=")) {
								dc.add(Restrictions.eq(field, s1));
							} else if (beanValue.startsWith(">")) {
								dc.add(Restrictions.gt(field, s1));
							} else if (beanValue.startsWith(">=")) {
								dc.add(Restrictions.ge(field,
										beanValue.substring(2)));
							} else if (beanValue.startsWith("<")) {
								dc.add(Restrictions.lt(field, s1));
							} else if (beanValue.startsWith("<=")) {
								dc.add(Restrictions.le(field,
										beanValue.substring(2)));
							} else if (beanValue.startsWith("%")) {
								dc.add(Restrictions.ilike(field, s1,
										MatchMode.END));
							} else if (beanValue.endsWith("%")) {
								dc.add(Restrictions.ilike(
										field,
										beanValue.substring(0,
												beanValue.length() - 1),
										MatchMode.START));
							} else {
								dc.add(Restrictions.ilike(field, beanValue,
										MatchMode.ANYWHERE));
							}
						} else if (StringUtils.endsWith(inputType, "date")) {
							// 对date进行情况判断
							if (beanValue.contains(" - ")) {
								// 时间阶段统计
								String[] ds = beanValue.split(" - ");
								dc.add(Restrictions.ge(field, ds[0])).add(
										Restrictions.le(field, ds[1]
												+ " 23:59:59"));
							} else {
								// 单天时间
								dc.add(Restrictions.ge(field, beanValue)).add(
										Restrictions.le(field, beanValue
												+ " 23:59:59"));
							}
						} else {
							dc.add(Restrictions.eq(field, beanValue));

						}
					}
				}

			}
		}
		return dc;
	}

	/**
	 * 由于本方法只用于比较，只针对in，==操作，所以原始对象、比较对象全部是String或者是StringList
	 * 用于edit（编辑页面显示、编辑数据）判断是否在编辑范围内 用于add（增加数据）是否在编辑范围内 输入：filter（List） 过滤条件
	 * 过滤条件中含有原始对象、比较方式、比较对象 原始对象有普通对象、二级对象（xx.xx）
	 * 比较对象，要求是最后被比较的值，不再在该方法中做转化（是否需要取id等，在FilterValue方法判断） 比较方式有in、=
	 * in：在比较对象范围内，普通对象：取得原始对象值，测试是否在比较对象范围内 ==：等于比较对象
	 * 
	 * @param filter
	 * @param bean
	 * @param service
	 * @return
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 */
	// public boolean isDataIn(HttpServletRequest request, Filter filter,
	// Object bean) throws IllegalAccessException, ClassNotFoundException,
	// InvocationTargetException, NoSuchMethodException {
	// boolean datain = true;
	// if (filter != null) {
	// if (StringUtils.isEmpty(filter.getType())
	// || StringUtils.equalsIgnoreCase("property",
	// filter.getType())) {
	// DetachedCriteria dcf = DetachedCriteria
	// .forClass(FilterProperty.class);
	// dcf.add(Restrictions.eq("filter", filter));
	// dcf.add(Restrictions.in("op", new String[] { "==", "in" }));
	// List<FilterProperty> fl = find(dcf);
	// if (CollUtil.isNotEmpty(fl)) {
	// for (FilterProperty f : fl) {
	// datain = false;
	// String op = f.getOp();
	// String propertyName = f.getProperty().getProperty();
	// Class<?> clazz = bean.getClass();
	// // String fvalue = "";
	// // int indexOf = propertyName.indexOf(".");
	// // if (indexOf >= 0) {
	// // String child = propertyName.substring(indexOf + 1,
	// // propertyName.length());
	// // String f1 = propertyName.substring(0, indexOf);
	// // Field declaredField = clazz.getDeclaredField(f1);
	// // Class<?> paramClazz = declaredField.getType();
	// // Object mem = (Object) declaredField.get(bean);
	// // if (mem != null) {
	// // Field childField = paramClazz
	// // .getDeclaredField(child);
	// // fvalue = String.valueOf(childField.get(mem));
	// // }
	// // } else {
	// // Field declaredField = clazz
	// // .getDeclaredField(propertyName);
	// // fvalue = String.valueOf(declaredField.get(bean));
	// // }
	// String fvalue = ReUtils.getStr(bean, propertyName);
	// if (StringUtils.isNotEmpty(fvalue)) {
	// // 被比较的原始值必须非空，若空，则无比较必要
	// Object filterValue = FilterVal.init(f.getVal())
	// .get();
	// if ("in".equals(op)) {
	// List<String> filterValueList = (List<String>) filterValue;
	// for (String b : filterValueList) {
	// if (fvalue.equals(b)) {
	// datain = true;
	// break;
	// }
	// }
	// } else if ("==".equals(op)) {
	// // String c="";
	// // if(filterValue instanceof Object){
	// // Field bfield =
	// // filterValue.getClass().getDeclaredField(
	// // Constant.ID);
	// // int bid = bfield.getInt(filterValue);
	// // c=String.valueOf(bid);
	// // }else{
	// // c=String.valueOf(filterValue);
	// // }
	// String c = (String) filterValue;
	// if (fvalue.equals(c)) {
	// datain = true;
	// }
	// }
	// }
	// if (!datain)// 多个filterProperty是串联关系，一个不通过就不通过。
	// break;
	// }
	// }
	// } else if (StringUtils.equalsIgnoreCase(filter.getType(), "js")) {
	// datain = false;
	// String js = filter.getFunc();
	// if (StringUtils.isNotEmpty(js)) {
	// ScriptEngineManager factory = new ScriptEngineManager();// step
	// ScriptEngine engine = factory.getEngineByName("JavaScript");// Step
	// engine.put("bean", bean);
	// engine.put("request", request);
	// // engine.put("createMemberId",);
	// try {
	// /*
	// * Object ca = ReUtils.getFieldValue(bean,
	// * "createMember"); String caId = ReUtils.getStr(ca,
	// * "id"); Object lg =
	// * request.getSession().getAttribute("SESSION_MEMBER");
	// * String lgId = ReUtils.getStr(lg, "id");
	// * if(StringUtils.equalsIgnoreCase(caId, lgId)){
	// * System.out.print("aaaaaa"); }else{
	// * System.out.print("nnnnnnn"); }
	// */
	// engine.eval(js);
	// datain = (Boolean) engine.get("cando");
	// } catch (ScriptException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	// }
	//
	// }
	// return datain;
	// }

	/**
	 * 本方法用于保存时，对于需要默认的字段进行赋值 只响应=，即赋值操作
	 * 
	 * @param filter
	 * @param service
	 * @param bean
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	// public void saveFilter(Filter filter, Object bean)
	// throws NoSuchFieldException, IllegalAccessException,
	// ClassNotFoundException {
	// DetachedCriteria dcf = DetachedCriteria.forClass(FilterProperty.class);
	// dcf.add(Restrictions.eq("filter", filter));
	// dcf.add(Restrictions.in("op", new String[] { "=" }));
	// List<FilterProperty> fl = find(dcf);
	// for (FilterProperty f : fl) {
	// String op = f.getOp();
	// String propertyName = f.getProperty().getProperty();
	// Field field = bean.getClass().getDeclaredField(propertyName);
	// if ("=".equals(op)) {
	// Object filterValue = FilterVal.init(f.getVal()).get();
	// field.set(bean, filterValue);
	// }
	// }
	// }

	/**
	 * 对于Bean的属性，定义了showvalue的，显示其属性值在cfg_cons表中对应的descr描述
	 * 
	 * @param bean
	 * @param listPl
	 * @param service
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 */
	@Deprecated
	@Transactional(readOnly = true)
	public void buildPropertyShowValue(Object bean, List<PerfProperty> listPl)
			throws NoSuchFieldException, IllegalAccessException,
			SecurityException, IllegalArgumentException,
			InvocationTargetException, NoSuchMethodException {
		for (PerfProperty pp : listPl) {
			final Property property = pp.getProperty();
			String showValue = JspUtil3.propertyValue(pp, "showvalue");
			if (StringUtils.isNotEmpty(showValue)) {
				String propertyName = property.getProperty();
				List<NameValuePair> nvlist = nvlist(showValue);
				String value = ReUtils.getStr(bean, propertyName);
				String name = "";
				for (NameValuePair nv : nvlist) {
					if (nv.getText().equals(value)) {
						name = nv.getId();
						break;
					}
				}
				ReUtils.set(bean, propertyName, name);
			}
		}
	}

	@Transactional(readOnly = true)
	public void buildPropertyShowValueInMap(Object bean,
			List<PerfProperty> listPl, String type)
			throws NoSuchFieldException, IllegalAccessException,
			SecurityException, IllegalArgumentException,
			InvocationTargetException, NoSuchMethodException,
			ClassNotFoundException, InstantiationException {
		for (PerfProperty pp : listPl) {
			final Property property = pp.getProperty();
			String propertyName = property.getProperty();
			if (propertyName.contains("sgabstract")) {
				String[] objectNames = propertyName.split("\\.");
				String objectName = objectNames[0];
				Object sg = ReUtils.get(bean, objectName);
				if (sg instanceof Map) {
					String sgClassName = ReUtils.getStr(sg, "$type$");
					DetachedCriteria dc = DetachedCriteria
							.forEntityName("com.sg.common.cfg.entity.TableBean");
					dc.add(Restrictions.eq("className", sgClassName));
					TableBean tableBean = findBean(dc);
					String descrProperty = tableBean.getDescrProperty();
					String descr = dealAbstract(descrProperty, sg);
					ReUtils.set(bean, property.getProperty(), descr);
				} else {
					String sgClassName = sg.getClass().getName();
					DetachedCriteria dc = DetachedCriteria
							.forEntityName("com.sg.common.cfg.entity.TableBean");
					dc.add(Restrictions.eq("className", sgClassName));
					TableBean tableBean = findBean(dc);
					String descrProperty = tableBean.getDescrProperty();
					String descr = dealAbstract(descrProperty, sg);
					ReUtils.set(bean, property.getProperty(), descr);
					System.out.println(sgClassName);
				}
			}
			String showValue = JspUtil3.propertyValue(pp, "showvalue");
			if (StringUtils.isNotEmpty(showValue)) {
				boolean change = true;
				// 为编辑状态下的控件显示属性，不需要转showvalue
				if (StringUtils.equals("edit", type)) {
					change = false;
					if (StringUtils.equals(pp.getEsh(), "1")) {
						change = true;
					}
				}
				if (change) {
					String value = ReUtils.getStr(bean, propertyName);
					Myinput myinput = JspUtil3.propertyMyinput(pp);
					String inputType = "";
					if (myinput != null) {
						inputType = myinput.getType();
					}
					String name = "";
					if (StringUtils.contains(showValue, "::")) {
						String[] split = showValue.split("::");

						String beanName = split[0];
						String descr = split[1];
						String[] ds = descr.split(",");
						String[] vals = StringUtils.split(value, " , ");
						for (String v : vals) {
							DetachedCriteria dc = DetachedCriteria
									.forEntityName(beanName);
							dc.add(Restrictions.eq("id", v));
							Object obj = findBean(dc);
							for (String d : ds) {
								name += ReUtils.getStr(obj, d) + " ";
							}
							name += " , ";
						}
					} else {
						String[] vals = StringUtils.split(value, " , ");
						for (String v : vals) {
							name += Constant.CONSMAP.get(showValue + "_" + v)
									+ " , ";
						}
					}
					if (StringUtils.isNotEmpty(name)) {
						name = StringUtils
								.substring(name, 0, name.length() - 3);
					}
					if (StringUtils.equals(name, "null")) {
						name = value;
					}
					ReUtils.set(bean, propertyName, name);
				}
			}
		}
	}

	private String dealAbstract(String func, Object bean)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		String res = func;
		if (StringUtils.isNotEmpty(func)) {
			List<String> funcs = new ArrayList<String>();

			while (func.indexOf("%%{") > 0) {
				int begin = func.indexOf("%%{");
				String right = func.substring(begin + 3);
				int end = right.indexOf("}");
				String para = right.substring(0, end);
				func = right;
				funcs.add(para);
			}
			for (String f : funcs) {
				String filtervalue = "";
				String className = "";
				if (bean instanceof Map)
					className = ReUtils.getStr(bean, "$type$");
				else
					className = bean.getClass().getName();

				Property p = Constant.BEANPROPMAP.get(className + "_" + f);
				if (p != null && StringUtils.isNotEmpty(p.getShowvalue())) {
					String value = ReUtils.getStr(bean, f);
					filtervalue = Constant.CONSMAP.get(p.getShowvalue() + "_"
							+ value);
					if (StringUtils.isEmpty(filtervalue)
							&& StringUtils.isNotEmpty(value))
						filtervalue = value;
				} else {
					filtervalue = ReUtils.getStr(bean, f);
				}

				if (StringUtils.isEmpty(filtervalue)) {
					filtervalue = "空";
				}
				String tar = "%%{" + f + "}";
				res = res.replace(tar, filtervalue);

			}
		}
		return res;
	}

	@Deprecated
	public void buildPropertyShowValueForEdit(Object bean,
			List<PerfProperty> pps) throws NoSuchFieldException,
			IllegalAccessException, SecurityException,
			IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException {
		for (PerfProperty pp : pps) {
			final Property property = pp.getProperty();
			String esh = pp.getEsh();
			String showValue = JspUtil3.propertyValue(pp, "showvalue");
			if (StringUtils.isNotEmpty(showValue)
					&& StringUtils.equals(esh, "1")) {// 只针对显示不编辑的属性进行转换
				String propertyName = property.getProperty();
				List<NameValuePair> nvlist = nvlist(showValue);
				String value = ReUtils.getStr(bean, propertyName);
				String name = "";
				for (NameValuePair nv : nvlist) {
					if (nv.getText().equals(value)) {
						name = nv.getId();
						break;
					}
				}
				if (StringUtils.isNotEmpty(name)) {
					ReUtils.set(bean, propertyName, name);
				}
			}
		}
	}

	public List<NameValuePair> findConstant(int domainId) {
		List<NameValuePair> res = new ArrayList<NameValuePair>();
		DetachedCriteria dc = DetachedCriteria.forClass(Cons.class);
		dc.add(Restrictions.eq("domain", get(Domain.class, domainId)));
		dc.add(Restrictions.eq("enable", "1"));
		List<Cons> findBean = find(dc);
		for (Cons cons : findBean) {
			NameValuePair nv = new NameValuePair();
			res.add(nv);
			nv.setId(cons.getName());
			nv.setText(cons.getValue());
		}
		return res;
	}

	public List<NameValuePair> findConstantSel(String domain) {
		List<NameValuePair> res = new ArrayList<NameValuePair>();
		DetachedCriteria dc = DetachedCriteria.forClass(Domain.class);
		dc.add(Restrictions.eq("domain", domain));
		Domain dom = findBean(dc);
		dc = DetachedCriteria.forClass(Cons.class);
		dc.add(Restrictions.eq("domain", dom));
		dc.add(Restrictions.eq("enable", "1"));
		dc.addOrder(Order.asc("ord"));
		List<Cons> findBean = find(dc);
		for (Cons cons : findBean) {
			NameValuePair nv = new NameValuePair();
			nv.setId(cons.getValue());
			nv.setText(cons.getName());
			res.add(nv);
		}
		return res;
	}

	public List<NameValuePair> nvlist(String domain2) {
		List<NameValuePair> nl = new ArrayList<NameValuePair>();
		nl.add(new NameValuePair("", ""));
		if (StringUtils.isNotEmpty(domain2)) {
			nl.addAll(findConstantSel(domain2));
		}
		return nl;
	}

	public List<AsyncTree> findTreeValue(Object bean, String id,
			List<String> endToTopPathIds, List<String> descrs)
			throws NoSuchFieldException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		List<AsyncTree> treeValue = new ArrayList<AsyncTree>();
		Object object = bean;
		if (StringUtils.isNotEmpty(id)) {
			object = get(bean.getClass(), id);
		}
		List<Object> pl = findByParent(object, bean);
		for (Object bo : pl) {
			AsyncTree at = new AsyncTree();

			String descrStr = ReUtils.mutiPropertyValue(descrs, bo);

			String boid = ReUtils.getStr(bo, "id");
//			at.setId(boid);
			at.setId(ReUtils.getStr(bo, "id"));
			at.setCode(ReUtils.getStr(bo, "code"));
			at.setLabel(descrStr.toString());
			if (endToTopPathIds.contains(boid)
					|| endToTopPathIds.contains("all")) {
				at.setChildren(findTreeValue(bean, boid, endToTopPathIds,
						descrs));
//				at.setState("open");
			} 
//				else {
//				if (CollUtil.isNotEmpty(findByParent(bo, bean))) {
//					at.setState("closed");
//				} else {
//					at.setState("open");
//				}
//			}
			treeValue.add(at);
		}
		return treeValue;
	}
		
	
	/**
	 * 用于查询 比较对象 ，注意不用分解到其ID（xxx.xx的形式） 只对in、==起作用。
	 * 
	 * @param dc
	 * @param filter
	 * @param service
	 * @throws ClassNotFoundException
	 */
	// public void createFilterDc(DetachedCriteria dc, Filter filter)
	// throws ClassNotFoundException {
	// if (filter != null) {
	// DetachedCriteria dcf = DetachedCriteria
	// .forClass(FilterProperty.class);
	// dcf.add(Restrictions.eq("filter", filter));
	// dcf.add(Restrictions.in("op", new String[] { "==", "in" }));
	// List<FilterProperty> fl = find(dcf);
	// // data filter
	// for (FilterProperty fp : fl) {
	// String op = fp.getOp();
	// String clazzStr = fp.getClazz();
	// // Class<?> clazzf = Class.forName(clazzStr);
	// String propertyName = fp.getProperty().getProperty();
	// if ("in".equals(op)) {
	// dc.add(Restrictions.in(propertyName,
	// (List) JspUtil3.filterValue(fp.getVal())));
	// } else if ("==".equals(op)) {
	// dc.add(Restrictions.eq(propertyName,
	// JspUtil3.filterValue(fp.getVal())));
	// }
	// }
	// }
	// }

}
